package com.ruoyi.feike.instener;

import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.EmailUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.domain.vo.ContractRecord;
import com.ruoyi.feike.mapper.*;
import com.ruoyi.feike.service.IAnnualReviewyService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

@Slf4j
@Component
public class SignedContractSendMailListener implements ExecutionListener , ApplicationContextAware {

    private Expression state;

    @Value("${spring.mail.from}") // 从application.yml配置文件中获取
    private String from; //  发送发邮箱地址

    @Value("${uat.url}") // 从application.yml配置文件中获取
    private String url; //  网址

    @Value("${uat.msg}") // 从application.yml配置文件中获取
    private String msg; //  网址

    @Value("${uat.isSendEmal}") // 从application.yml配置文件中获取
    private String isSendEmal; //  网址

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private BasicInformationMapper basicInformationMapper;

    @Autowired
    private AnnualReviewyMapper annualReviewyMapper;

    private static ApplicationContext context = null;

    @Override
    public void notify(DelegateExecution delegateExecution) {
        log.info("开始发办结邮件");
        ArrayList<String> userNames = new ArrayList<>();
        userNames.add(SecurityUtils.getUsername());
        ArrayList<SysUser> users = new ArrayList<>();
        String activeProfile = context.getEnvironment().getActiveProfiles()[0];
        if(activeProfile.equals("dev")){
            isSendEmal = "true";
            url = "http://localhost:81";
            from ="Service.IT@stellantisafc.com.cn";
            msg ="【UAT测试邮件】";
        }else if(activeProfile.equals("prod")){
            isSendEmal = "true";
            url = "http://10.226.185.146:81";
            from ="Service.IT@stellantisafc.com.cn";
            msg ="";
        }else if (activeProfile.equals("uat")){
            isSendEmal = "true";
            url = "http://10.226.186.143:82";
            from ="Service.IT@stellantisafc.com.cn";
            msg ="【UAT测试邮件】";
        }
        //需要更新状态
        String businessKey =null ;
        String instanceId = delegateExecution.getProcessInstanceId();
        List<DealercodeContractFiling> dealercodeContractFilings = null;
        if(null !=instanceId){
            HistoryService historyService = SpringUtils.getBean(HistoryService.class);
            ISysUserService userService = SpringUtils.getBean(ISysUserService.class);
            List<HistoricTaskInstance> taskInstance = historyService.createHistoricTaskInstanceQuery().processInstanceId(instanceId).list();
            HistoricProcessInstance procInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(instanceId).singleResult();
            businessKey = procInstance.getBusinessKey();

            ContractRecordMapper contractRecordMapper = SpringUtils.getBean(ContractRecordMapper.class);
            DealercodeContractFilingMapper dealercodeContractFilingMapper = SpringUtils.getBean(DealercodeContractFilingMapper.class);
            IAnnualReviewyService annualReviewyService = SpringUtils.getBean(IAnnualReviewyService.class);
            AnnualReviewyMapper mapper = SpringUtils.getBean(AnnualReviewyMapper.class);
            AnnualReviewy annualReviewy = mapper.selectAnnualReviewyByInstanceId(businessKey);
            if(annualReviewy !=null  && annualReviewy.getDealerName() !=null && annualReviewy.getSector() !=null && annualReviewy.getLimitType()!=null) {
                String note =null;
                String[] split = businessKey.split("-");
                ContractRecord newContractRecord = new ContractRecord();
                newContractRecord.setInstanceid(split[0]);
                newContractRecord.setDealername(annualReviewy.getDealerName());
                newContractRecord.setSector(annualReviewy.getSector());
                newContractRecord.setLimitType(annualReviewy.getLimitType());
                List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordList(newContractRecord);
                for (ContractRecord contractRecord : contractRecords) {
                    if(!StringUtils.isEmpty(contractRecord.getScenario())){
                        note = contractRecord.getScenario();
                        break;
                    }
                }
                DealerSectorContractgroupMapper bean = SpringUtils.getBean(DealerSectorContractgroupMapper.class);
                String contractnumber = null;
                DealerSectorContractgroup dealerSectorContractgroup = new DealerSectorContractgroup();
                dealerSectorContractgroup.setDealername(annualReviewy.getDealerName());
                dealerSectorContractgroup.setSector(annualReviewy.getSector());
                dealerSectorContractgroup.setContractname("人民币循环贷款合同");
                List<DealerSectorContractgroup> dealerSectorContractgroups = bean.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                if(dealerSectorContractgroups!=null && dealerSectorContractgroups.size()>0){
                    String contractnumber1 = dealerSectorContractgroups.get(0).getContractnumber();
                    StringBuilder stringBuilder = new StringBuilder(contractnumber1);
                    if(annualReviewy.getLimitType().equals("Demo")){
                        contractnumber = stringBuilder.replace(6,7,String.valueOf("DEMO")).toString();
                    } else if(annualReviewy.getLimitType().equals("CB")){
                        contractnumber = stringBuilder.replace(6,7,String.valueOf("CB")).toString();
                    }else {
                        contractnumber = contractnumber1;
                    }
                }else{
                    if(annualReviewy.getLimitType().equals("Demo")){
                        DealerSectorContractgroup dealerSectorContractgroup1 = new DealerSectorContractgroup();
                        dealerSectorContractgroup1.setDealername(annualReviewy.getDealerName());
                        dealerSectorContractgroup1.setSector(annualReviewy.getSector());
                        dealerSectorContractgroup1.setContractname("试乘试驾车贷款合同");
                        List<DealerSectorContractgroup> dealerSectorContractgroups1 = bean.selectDealerSectorContractgroupList(dealerSectorContractgroup1);
                        if(dealerSectorContractgroups1!=null && dealerSectorContractgroups1.size()>0){
                            contractnumber = dealerSectorContractgroups1.get(0).getContractnumber();
                        }
                    }
                }


                DealercodeContractFiling newDealercodeContractFiling = new DealercodeContractFiling();
                newDealercodeContractFiling.setSubProcessId(businessKey);
                newDealercodeContractFiling.setInstanceId(split[0]);
                newDealercodeContractFiling.setDealerNameCN(annualReviewy.getDealerName());
                newDealercodeContractFiling.setSector(annualReviewy.getSector());
                newDealercodeContractFiling.setLimitType(annualReviewy.getLimitType());
                dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingList(newDealercodeContractFiling);
                if(dealercodeContractFilings!=null && dealercodeContractFilings.size()>0){
                    for (DealercodeContractFiling dealercodeContractFiling : dealercodeContractFilings) {
                        dealercodeContractFiling.setNote(note);
                        dealercodeContractFiling.setContractno(contractnumber);
                        //查询是否有PART
                        ContractRecord record = new ContractRecord();
                        record.setInstanceid(dealercodeContractFiling.getInstanceId());
                        record.setDealername(dealercodeContractFiling.getDealerNameCN());
                        record.setSector(dealercodeContractFiling.getSector());
                        record.setLimitType(dealercodeContractFiling.getLimitType());
                        List<ContractRecord> contractRecordList = contractRecordMapper.selectContractRecordList(record);
                        if(contractRecordList!=null && contractRecordList.size()>0){
                            ContractRecord contractRecord = contractRecordList.get(0);
                            if(StringUtils.isNotNull(contractRecord.getPartsAmount())){
                                dealercodeContractFiling.setPartsAmount(contractRecord.getPartsAmount());
                            }
                        }

                    }
                }

                List<String> workflowFormData = annualReviewyService.getWorkflowFormData(split[0]);
                userNames.add(annualReviewy.getCreateBy());
                //查询credit用户
                SysUserMapper sysUserMapper = SpringUtils.getBean(SysUserMapper.class);
                List<String> uws = sysUserMapper.getuwNamesByPostCode("underwriter");
                List<String> sales = sysUserMapper.getuwNamesByPostCode("supervisor");
                List<String> credits = sysUserMapper.getuwNamesByPostCode("credit manager");
                for (String account : workflowFormData) {
                    if(!account.equals("af261") && !account.equals("af252")){
                        if(!uws.contains(account) && !sales.contains(account) && !credits.contains(account)){
                            userNames.add(account);
                        }
                    }
                }
                LinkedHashSet<String> hashSet = new LinkedHashSet<>(userNames);
                ArrayList<String> listWithoutDuplicates = new ArrayList<>(hashSet);
                System.out.println("邮件接收人:"+listWithoutDuplicates);
                for (String listWithoutDuplicate : listWithoutDuplicates) {
                    SysUser sysUser = userService.selectUserByUserName(listWithoutDuplicate);
                    if(sysUser != null && sysUser.getEmail()!=null){
                        users.add(sysUser);
                    }
                }

            }
        }
        if(isSendEmal!=null && isSendEmal.equals("true") && users.size()>0) {
            for (SysUser user : users) {
                //发送邮件
                sendMailByEmailInfo(user, businessKey,dealercodeContractFilings);
            }
        }
    }

    public void sendMailByEmailInfo(SysUser user, String instanceId, List<DealercodeContractFiling> dealercodeContractFilings) {
        try {
            StringBuilder contentStr = new StringBuilder();
            String dealerName ="";
            String ln = "<br>";
            StringBuilder content = new StringBuilder("<html><head></head><body><h3>合同信息</h3>");
            content.append("<table border=\"5\" style=\"border:solid 1px #E8F2F9;font-size:16px;\">");
            content.append("<tr style=\"background-color: #428BCA; color:#ffffff\"><th>Instanceld</th><th>Sector</th><th>DealerName</th><th>Contract No</th><th>Deposit</th><th>FacilityAmount</th><th>PartFacilityAmount</th><th>ExpiryDate</th><th>EffectiveDate</th><th>Note</th></tr>");
            if(dealercodeContractFilings!=null && dealercodeContractFilings.size()>0){
                dealerName = dealercodeContractFilings.get(0).getDealerNameCN();
                for (DealercodeContractFiling contract : dealercodeContractFilings) {
                    content.append("<tr>");
                    content.append("<td>" + contract.getInstanceId() + "</td>"); //第一列
                    content.append("<td>" + contract.getSector() + "</td>"); //第二列
                    content.append("<td>" + contract.getDealerNameCN() + "</td>"); //第三列
                    content.append("<td>" + contract.getContractno() + "</td>"); //第四列
                    content.append("<td>" + contract.getDeposit() + "</td>"); //第五列
                    BigDecimal bigDecimal = new BigDecimal(contract.getFacilityAmount());
                    BigDecimal bigDecimal1 = bigDecimal.divide(new BigDecimal(1000000));
                    String Amt = bigDecimal1.toString() + "M";
                    content.append("<td>" + Amt + "</td>"); //第六列
                    if(StringUtils.isNotNull(contract.getPartsAmount()) && !contract.getPartsAmount().equals("/") ){
                        BigDecimal bigDecimalPart = new BigDecimal(contract.getPartsAmount());
                        BigDecimal bigDecimal1Part = bigDecimalPart.divide(new BigDecimal(1000000));
                        String Amt1 = bigDecimal1Part.toString() + "M";
                        content.append("<td>" + Amt1 + "</td>"); //第七列
                    }else{
                        content.append("<td>" + "/" + "</td>"); //第七列
                    }
                    content.append("<td>" + contract.getExpiredDate() + "</td>"); //第七列
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String format = sdf.format(contract.getEffectiveDate());
                    content.append("<td>" + format + "</td>"); //第八列
                    content.append("<td>" + contract.getNote() + "</td>"); //第九列
                    content.append("</tr>");

                }
            }
            content.append("</table>");
            content.append("</body></html>");
            contentStr.append(msg);
            contentStr.append(ln);
            contentStr.append(dealerName);
            contentStr.append(ln);
            contentStr.append(content);
            // 测试文本邮件发送（无附件）
            String to = user.getEmail();
            if(!StringUtil.isEmpty(to)){
                System.out.println("发送任务到"+ to);
                String title = "合同已完成--"+dealerName;
                //带附件方式调用
                JavaMailSender bean = SpringUtils.getBean(JavaMailSender.class);
                new EmailUtil(from, bean).sendMessageCarryFiles(to, title, contentStr.toString(), null);
                // return AjaxResult.success();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}
